package com.jeecg.study.form;

import java.io.File;
import java.lang.reflect.Field;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.jeecg.study.common.utils.Global;

/**
 * @see 通过反射实现表单提交的数据和实体绑定
 * @author wuhn
 *
 */
public class FullForm {
	
	private FullForm(){
		
	}
	
	/**
	 * @see 将请求的表单数据和class绑定
	 * @param classPath  class 路径
	 * @param request 
	 * @return
	 */
	public static ActionForm bindForm(String classPath,HttpServletRequest request){
		ActionForm form = null;
		Class<?> clzz=null;
		try {
			clzz = Class.forName(classPath);
			form = (ActionForm)clzz.newInstance();
			Field[] fields = clzz.getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true);
				setValuesByType(field,form,request);
				field.setAccessible(false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return form;
	}
	
	/**
	 * @see 根据对应的Class类型，给反射给实体赋值。
	 * @param field
	 * @param form
	 * @param request 
	 */
	private static  void setValuesByType(Field field, ActionForm form,HttpServletRequest request) {
		if(field.getType() == String.class ){
			try {
				field.set(form,request.getParameter(field.getName()) );
			} catch (IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
			}
		}else if(field.getType().equals(Integer.class)){
			try {
				if(StringUtils.isNotBlank(request.getParameter(field.getName()))){
					field.set(form,Integer.valueOf(request.getParameter(field.getName())));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if(field.getType() == Boolean.class){
			try {
				boolean bool = request.getParameter(field.getName()).equals("1")?true:false;
				field.set(form, Boolean.valueOf(bool));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
}
